package com.zhongjian.technologycal.mall.activity.main.activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.zhongjian.greendaomall.greendao.gen.DaoMaster;
import com.zhongjian.greendaomall.greendao.gen.DaoSession;
import com.zhongjian.greendaomall.greendao.gen.UserBeanDao;
import com.zhongjian.technologycal.mall.R;
import com.zhongjian.technologycal.mall.base.BaseActivity;
import com.zhongjian.technologycal.mall.bean.UserBean;
import com.zhongjian.technologycal.mall.utils.StatusBarUtil;
import com.zhongjian.technologycal.mall.utils.ToastUitl;
import com.zhongjian.technologycal.mall.view.ClearEditText;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by wei on 2017/11/8.
 * 通过关键字搜索商品
 */

public class SearchDataActivity extends BaseActivity {
    @BindView(R.id.tv_cancel)
    TextView tv_cancel;
    @BindView(R.id.flowLayout_search)
    TagFlowLayout mFlowLayout;
    @BindView(R.id.search_clear_edittext)
    ClearEditText search_clear_edittext;
    @BindView(R.id.flowLayout_hot)
    TagFlowLayout flowLayout_hot;
    @BindView(R.id.ll_search)
    LinearLayout ll_search;
    private String[] tags ;
    private String[] tagsHot = new String[]{
            "陈政壹号", "眼镜", "酸奶", "木耳", "同江大米",
            "四件套", "眼镜", "面膜", "黑木耳", "大米", "枸杞"

    };
    private UserBeanDao userBeanDao;
    private UserBean userBean;
    private int status = 0;
    private Dialog hintDialog = null;

    private TagAdapter<String> mAdapter;
    private List<UserBean> userList;

    @Override
    protected void initView(Bundle savedInstanceState) {
        DaoMaster.DevOpenHelper devOpenHelper = new
                DaoMaster.DevOpenHelper(
                getApplicationContext(), "zhongjianmall.db", null);
        DaoMaster daoMaster = new DaoMaster(devOpenHelper.getWritableDb());
        DaoSession daoSession = daoMaster.newSession();
        userBeanDao = daoSession.getUserBeanDao();
        initTextChange();
        initViewInput();
        queryDataBaseData();
        setDataFlowLayout();
    }

    @Override
    protected void beforeInit() {
        super.beforeInit();
        //状态栏着色
//        StatusBarUtil.setColorNoTranslucent(this, getResources().getColor(R.color.border_color));
//        StatusBarUtil.setMiuiStatusBarDarkMode(this, true);

    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_search_layout;
    }

    @Override
    public void initPresenter() {

    }

    /**
     * 1) 填充FlowLayout数据
     * 2）为FlowLayout设置点击事件
     */
    private void setDataFlowLayout() {
        final LayoutInflater mInflater = LayoutInflater.from(this);
        mFlowLayout.setAdapter(mAdapter = new TagAdapter<String>(tags) {
            @Override
            public View getView(FlowLayout parent, int position, String str) {
                TextView tags = (TextView) mInflater.inflate(R.layout.tags_flowlayout_tv,
                        mFlowLayout, false);
                tags.setText(str);
                return tags;
            }
        });
        mFlowLayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                Intent intent = new Intent();
                intent.setClass(getBaseContext(), KeywordSearchListActivity.class);
                intent.putExtra("keywordTags", tags[position]);
                startActivity(intent);
                return true;
            }
        });

        flowLayout_hot.setAdapter(mAdapter = new TagAdapter<String>(tagsHot) {
            @Override
            public View getView(FlowLayout parent, int position, String str) {
                TextView tv_tagshot = (TextView) mInflater.inflate(R.layout.tags_flowlayout_tv,
                        flowLayout_hot, false);
                tv_tagshot.setText(str);
                return tv_tagshot;
            }
        });

        flowLayout_hot.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                Intent intent = new Intent();
                intent.setClass(getBaseContext(), KeywordSearchListActivity.class);
                intent.putExtra("keywordTags", tagsHot[position]);
                startActivity(intent);
                return true;
            }
        });
    }

    //添加数据
    private void insertSetData(String title, String nickname) {
        userBean = new UserBean(null, title, nickname);
        userBeanDao.insert(userBean);
    }

    //查询数据
    private void queryDataBaseData() {
        userList = userBeanDao.queryBuilder()
                .where(UserBeanDao.Properties.Id.notEq(999))
                .orderDesc(UserBeanDao.Properties.Id)
                .limit(2000)
                .build().list();
        tags = new String[userList.size()];
        for (int i = 0;i< userList.size(); i++) {
            tags[i] = userList.get(i).getUsername();
            Log.i("hhh",tags[i]);
        }


    }

    private void initTextChange() {
        search_clear_edittext.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (search_clear_edittext.getText().toString().length() > 0) {
                    status = 0;
                    tv_cancel.setText("搜索");
                } else {
                    status = 1;
                    tv_cancel.setText("取消");

                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });


    }

    private void initViewInput() {
        search_clear_edittext.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEND || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    if (TextUtils.isEmpty(search_clear_edittext.getText().toString())) {
                        ToastUitl.showShort("输入关键字不能为空.");
                    } else {
                        insertSetData(search_clear_edittext.getText().toString(), "");
                        Intent intent = new Intent();
                        intent.setClass(getBaseContext(), KeywordSearchListActivity.class);
                        intent.putExtra("keywordTags", search_clear_edittext.getText().toString().trim());
                        startActivity(intent);
                        finish();
                    }

                }
                return false;
            }
        });
    }

    @OnClick(R.id.tv_cancel)
    public void appClickCancel() {
        if (status == 0) {
            if (TextUtils.isEmpty(search_clear_edittext.getText().toString())) {
                finish();
            } else {
                insertSetData(search_clear_edittext.getText().toString(), "");
                Intent intent = new Intent();
                intent.setClass(getBaseContext(), KeywordSearchListActivity.class);
                intent.putExtra("keywordTags", search_clear_edittext.getText().toString());
                startActivity(intent);
            }

        } else {
            finish();
        }

    }

    public void refresh() {
        finish();
        Intent intent = new Intent(getBaseContext(), SearchDataActivity.class);
        startActivity(intent);
    }
    @OnClick(R.id.iv_delete)
    public void onClickDeleteData(){
        hintDialog = getDialog.getHintDialog(this, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                userBeanDao.deleteAll();
                mFlowLayout.removeAllViews();
                userList.remove(userBean);
                setDataFlowLayout();
                mFlowLayout.invalidate();
                refresh();
                hintDialog.dismiss();
            }
        },"确定清空搜索历史吗？",true);
        hintDialog.show();

    }

    @Override
    protected void onResume() {
        super.onResume();
        queryDataBaseData();
        setDataFlowLayout();
    }
}
